/**
 * 
 */
package core.internal.builder.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import core.internal.SystemDirectory;
import core.internal.SystemFile;
import core.internal.SystemItem;

/**
 * @author cipri
 *
 */
public class FileSystemBuilder extends Builder
{
    private SystemDirectory _root; 
    
    public void parseDirectory(File root) throws FileNotFoundException
    {
        _root = new SystemDirectory(root.getName());
        parseDirectory(root, _root);
    }
    
    private void parseDirectory(File dir, SystemItem item) throws FileNotFoundException
    {
        validateDirectory(dir);
        
        File[] filesAndDirs = dir.listFiles();
        List<File> filesDirs = Arrays.asList(filesAndDirs);
        SystemItem currentItem = new SystemDirectory(dir.getName());
    
        for(File file : filesDirs) 
        {
            if (file.isFile())
            {
                //we have a file
                BufferedReader line = new BufferedReader(new FileReader(file));
                String content = "";
                try
                {
                    //String currentLine = "";
                    //while (currentLine = line.readLine() != EOF)
                    //{
                    // aici ar trebui citit tot continutul fisierului
                    //}
                    content = line.readLine();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                currentItem = new SystemFile(file.getName(), content);
                item.add(currentItem);
            }
            else if (file.isDirectory())
            {
                //we have a directory -> parse
                currentItem = new SystemDirectory(file.getName());
                item.add(currentItem);
                parseDirectory(file, currentItem);
            }
        }
    }
    
    /**
     * Directory is valid if it exists, does not represent a file, and can be read.
     */
     private void validateDirectory (File dir) 
             throws FileNotFoundException 
     {
       if (dir == null) 
       {
           throw new IllegalArgumentException("Directory should not be null.");
       }
       if (!dir.exists()) 
       {
           throw new FileNotFoundException("Directory does not exist: " + dir);
       }
       if (!dir.isDirectory()) 
       {
           throw new IllegalArgumentException("Is not a directory: " + dir);
       }
       if (!dir.canRead()) 
       {
           throw new IllegalArgumentException("Directory cannot be read: " + dir);
       }
     }
     
     public SystemItem getRoot()
     {
         return _root;
     }
}
